<script>
import EditBookInfo from "./components/editBookInfo.vue"
import loginInfo from "./util/loginInfo";
export default {
    components: {
        EditBookInfo
    },
    data() {
        return {
            tableData: [
                // {
                //     "bookId": 123,
                //     "bookName": "c++程序设计教程（通用版）（第三版）",
                //     "bookAuthor": "钱能",
                //     "bookISBN": "978-7825-1236-789",
                //     "bookPress": "湖南大学出版社",
                //     "bookExistingNumber": 1, // 现存总数量
                //     "bookTotalNumber": 16 // 总数量
                // }
            ],
            searchForm: {
                name: '',
                isbn: '',
                author: '',
            },
            pagination: {
                pageSize: 10,
                currentPage: 1,
                total: 1
            },
            addDialogVisible: false,
            editingBook: {},
            dialogVisible: false,
            editingBookIndex: 0
        }
    },
    async mounted() {
        this.$http.get('/books', {
            headers: {
                'token': loginInfo.getToken()
            }
        }).then((v) => {
            this.tableData = v.data.books
            this.pagination.total = v.data['total-count']
        })
    },
    methods: {
        editBook(index) {
            this.dialogVisible = true;
            this.editingBookIndex = index
            this.editingBook = { ...this.tableData[index] }
        },
        addBook() {
            this.addDialogVisible = true;
            this.editingBookIndex = 0
            this.editingBook = {
                "bookName": "",
                "bookAuthor": "",
                "bookISBN": "",
                "bookPress": "",
                "bookExistingNumber": 0, // 现存总数量
                "bookTotalNumber": 0 // 总数量
            }
        },
        onSaveAddBook(data) {
            data.bookExistingNumber = data.bookTotalNumber
            this.$http.post(`/books`, {
                "bookName": data.bookName,
                "bookAuthor": data.bookAuthor,
                "bookISBN": data.bookISBN,
                "bookPress": data.bookPress,
                "bookExistingNumber": data.bookExistingNumber,
                "bookTotalNumber": data.bookTotalNumber
            }, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status == 200) {
                    this.$message.success('新增成功')
                    if (this.addDialogVisible) {
                        this.addDialogVisible = false;
                    }
                    this.tableData.unshift({ ...data, bookId: v.data.bookId })
                } else {
                    this.$message.error(v.msg)
                }
            })
        },
        onCurrentPageChange(val) {
            this.pagination.currentPage = val
            this.onSearch()
        },
        onPageSizeChange(val) {
            this.pagination.currentPage = 1
            this.pagination.pageSize = val
            this.onSearch()
        },
        onSearch(clickBtn = false) {
            if (clickBtn) {
                this.pagination.currentPage = 1
            }
            let obj = {}
            let form = this.searchForm
            if (form.name !== '') {
                obj.name = form.name
            }
            if (form.isbn !== '') {
                obj.isbn = form.isbn
            }
            if (form.author !== '') {
                obj.author = form.author
            }

            obj.page = this.pagination.currentPage
            obj['page-size'] = this.pagination.pageSize

            this.$http.get('/books', {
                headers: {
                    'token': loginInfo.getToken()
                },
                params: {
                    ...obj
                }
            }).then((v) => {
                this.tableData = v.data.books
                this.pagination.total = v.data['total-count']
            })
        },
        onSave(data) {
            console.log(data)
            this.$http.put(`/books/${data.bookId}`, {
                "bookName": data.bookName,
                "bookAuthor": data.bookAuthor,
                "bookISBN": data.bookISBN,
                "bookPress": data.bookPress,
                "bookExistingNumber": data.bookExistingNumber,
                "bookTotalNumber": data.bookTotalNumber
            }, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status == 200) {
                    this.$message.success('修改成功！')
                    this.dialogVisible = false;
                    this.tableData[this.editingBookIndex] = { ...data }
                } else {
                    this.$message.error(v.msg)
                }
            })
        },
        onRemoveBook(index, id) {
            this.$http.delete(`/books/${id}`, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status === 200) {
                    this.$message.success('删除成功!');
                    this.onSearch();
                } else {
                    this.$message.warning(v.msg);
                }
            })
        },
        onSearchRecords(bookId) {
            this.$router.push({ path: '/records', query: { bookId } })
        },
        cellClick(row, column, cell, event) {
            console.log(row)
            if (column.no == 1) {
                this.searchForm.name = row.bookName
            }
            if (column.no == 2) {
                this.searchForm.author = row.bookAuthor
            }
        }
    }
}
</script>

<template>
    <div>
        <el-card shadow="never">
            <el-form :inline="true">
                <el-form-item label="图书名称">
                    <el-input clearable v-model="searchForm.name" placeholder="图书名称"></el-input>
                </el-form-item>
                <el-form-item label="ISBN">
                    <el-input clearable v-model="searchForm.isbn" placeholder="ISBN"></el-input>
                </el-form-item>
                <el-form-item label="作者">
                    <el-input clearable v-model="searchForm.author" placeholder="作者"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button @click="onSearch" icon="search" type="primary">搜索</el-button>
                </el-form-item>
            </el-form>
            <el-table
                @cell-click="cellClick"
                :height="350"
                :data="tableData"
                border
                style="margin: 20px 0;width: 100%"
            >
                <el-table-column prop="bookId" label="图书ID" width="100" />
                <el-table-column show-overflow-tooltip prop="bookName" label="图书名称" />
                <el-table-column prop="bookAuthor" label="作者" width="180" />
                <el-table-column prop="bookISBN" label="ISBN" width="180" />
                <el-table-column
                    show-overflow-tooltip
                    prop="bookPress"
                    label="出版社"
                    max-width="180"
                />
                <el-table-column prop="bookExistingNumber" label="现存数量" width="90" />
                <el-table-column prop="bookTotalNumber" label="总数量" width="80" />
                <el-table-column label="操作" width="400">
                    <template #header>
                        <span style="margin-right: 10px;">操作</span>
                        <el-button @click="addBook" type="success" icon="plus">新增图书</el-button>
                    </template>
                    <template #default="scope">
                        <el-button
                            @click="onSearchRecords(scope.row.bookId)"
                            type="success"
                            plain
                            icon="search"
                        >查询借阅记录</el-button>
                        <el-button type="warning" icon="edit" @click="editBook(scope.$index)">编辑</el-button>
                        <el-popconfirm
                            confirm-button-text="确定"
                            cancel-button-text="取消"
                            icon="InfoFilled"
                            @confirm="onRemoveBook(scope.$index, scope.row.bookId)"
                            icon-color="red"
                            title="确定要删除吗？"
                        >
                            <template #reference>
                                <el-button type="danger" icon="delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @current-change="onCurrentPageChange"
                @size-change="onPageSizeChange"
                :page-sizes="[10, 15, 20]"
                background
                :current-page="pagination.currentPage"
                layout="sizes, prev, pager, next, jumper"
                :total="pagination.total"
            ></el-pagination>
        </el-card>
        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="'编辑图书 ' + editingBook.bookId">
            <EditBookInfo @submit="onSave" :data="editingBook"></EditBookInfo>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 新增对话框 -->
        <el-dialog v-model="addDialogVisible" :title="'新增图书 '">
            <EditBookInfo @submit="onSaveAddBook" :data="editingBook"></EditBookInfo>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style>
</style>